package edu.cque.hello;

import edu.cque.hello.util.Db;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

/**
 * @author Hua
 * @create 2022-03-25 16:00
 */
@RequestMapping("car2")
@RestController  //是springmvc提供的,可以被浏览器访问
public class CarController2 {
    @RequestMapping("show")
    public String show() {
        return "浏览器访问成功";
    }


    //框架作用: 1, 解析了请求参数,2,把解析的参数调用XX.set()方法设置值.
    @RequestMapping("save")
    public Car save(Car car) {
        System.out.println("car = " + car);
        return car;
    }

    @RequestMapping("login")
    public String login(String name, String loc) {
        Connection connection = null;
        ResultSet resultSet = null;
        Statement statement = null;
        try {
            connection = Db.getConnection();

            //3, 定义SQL
//            String sql = "select * from dept where dname = '" + name + "'and loc ='" + loc + "' ";
            String sql = "insert into dept (dname,loc) values(?,?)";
            System.out.println(sql);
            //4,获取传输器
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setString(2,loc);
            //5, 处理结果集
            int execute = preparedStatement.executeUpdate();
            System.out.println("execute = " + execute);
            if ( execute == 1) {
//                System.out.println("登录成功");
                return "插入成功";
            } else {
                System.out.println("插入失败");
                return "插入失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//        6, 释放资源
            Db.close(resultSet, statement, connection);
        }
        return name+loc;
    }


}
